package com.jojo.bubble.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.jojo.bubble.common.domain.AjaxResult;
import com.jojo.bubble.entity.User;
import com.jojo.bubble.dao.UserDao;
import com.jojo.bubble.service.UserService;
import com.jojo.bubble.utils.HttpClientUtil;
import com.jojo.bubble.utils.WeChatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import static com.jojo.bubble.utils.AlipayTradeWapPay.authLogin;

/**
 * 用户表(User)表服务实现类
 *
 * @author jojo
 * @since 2023-07-22 07:31:36
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public int count(User record) {
        return this.userDao.count(record);
    }

    @Override
    public int insert(User record) {
        return this.userDao.insert(record);
    }

    @Override
    public int update(User record) {
        return this.userDao.update(record);
    }

    @Override
    public User getInfo(int id) {
        return this.userDao.queryById(id);
    }

    @Override
    public List<User> getList(User record) {
        return this.userDao.getList(record);
    }

    @Override
    public int delete(int id) {
        return this.userDao.delete(id);
    }

    @Override
    public AjaxResult toWeChatLogin(String code) {

        //微信服务器接口
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatUtil.appid + "&secret=" + WeChatUtil.secret + "&code=";
        url += code + "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtil.sendGet(url);
        String scope = jsonObject.getString("scope");
        if (StringUtils.isNotEmpty(scope)) {
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            String getUserUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
            JSONObject userJSON = HttpClientUtil.sendGet(getUserUrl);
            User user = updateUserInfo(userJSON);
            return AjaxResult.success(user);
        }
        return AjaxResult.error("微信登录失败");
    }

    @Override
    public AjaxResult toAliLogin(String code) throws AlipayApiException {
        User user = authLogin(code);
        if (StringUtils.isNotEmpty(user.getOpenId())){
            User record = userDao.getUserByOpenId(user.getOpenId());
            if (ObjectUtils.isEmpty(record)) {
                userDao.insert(user);
            } else {
                if (!user.getAvatar().equals(record.getAvatar()) || !user.getNickname().equals(record.getNickname())) {
                    record.setAvatar(user.getAvatar());
                    record.setNickname(user.getNickname());
                    userDao.update(record);
                    user = record;
                }
            }
            return AjaxResult.success(user);
        }
        return AjaxResult.error("支付宝登录失败");


    }

    @Override
    public User queryByOpenId(String openId) {
        return userDao.getUserByOpenId(openId);
    }

    private User updateUserInfo(JSONObject userJSON) {
        String openId = "";
        User u = new User();

        String nickname = userJSON.getString("nickname");
        openId = userJSON.getString("openid");
        String avatar = userJSON.getString("headimgurl");
        if (StringUtils.isNotEmpty(openId)) {

            User user = userDao.getUserByOpenId(openId);
            if (ObjectUtils.isEmpty(user)) {
                if (StringUtils.isNotEmpty(nickname)) {
                    u.setNickname(nickname);
                }
                if (StringUtils.isNotEmpty(avatar)) {
                    u.setAvatar(avatar);
                }
                u.setCreateTime(new Date());
                u.setOpenId(openId);
                u.setSubscribe(1);
//                u.setId(0);
                userDao.insert(u);
            } else {
                if (StringUtils.isNotEmpty(nickname)) {
                    user.setNickname(nickname);
                }
                if (StringUtils.isNotEmpty(avatar)) {
                    user.setAvatar(avatar);
                }
                user.setSubscribe(1);
                userDao.update(user);
                u = user;
            }
        }
        return u;
    }
}
